/* Copyright  2009-2010
   @Author
   Richard Changde Yin            e-mail yinchangde@hotmail.com


   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

/**
 * @filename: chunkiterator.cc
 */
#include<server_includes.h>
#include<allocator.h>
#include<database.h>
#include<os.h>
#include<debug.h>

#include <util.h>
#include <error.h>

using namespace BackEnd ;
//No iterators for variable size allocators

void* ChunkIterator::nextElement()
{
      if (0 == noOfNodes_)
     {
       //means tuple larger than PAGE_SIZE
       if(NULL == iterPage_) return NULL;
       char *record =NULL;
       record = ((char*)iterPage_) +sizeof(PageInfo);
         while(*(int*)record != 1)
       {
         iterPage_ = (PageInfo*) iterPage_->nextPage_;
         if(NULL == iterPage_) return NULL;
         record = ((char*)iterPage_)  +sizeof(PageInfo);
       }
       iterPage_ = (PageInfo*) iterPage_->nextPage_;
       return (record + sizeof(int));
     }
      //check whether there are any nodes in the current page
     if (!data) {
        data = ((char*)iterPage_) + sizeof(PageInfo);
        if ((*(int*)data) == 1)
            return data + sizeof(int);
      }
         data = data + allocSize_;
         while(data < iterPageEnd)
      {
           if (*((int*)data) == 0)
          {
             //not used, so skip it
              data = data + allocSize_;
          }
            else
            {
               //used, return element pointer
                return data + sizeof(int);
            }
          }
        //go to next page and check till it exhausts
           while(iterPage_->nextPage_ != NULL)
        {
           iterPage_ = (PageInfo*)iterPage_->nextPage_;
           data = ((char*)iterPage_) + sizeof(PageInfo);
           iterPageEnd = ((char*)iterPage_) + PAGE_SIZE;
           while(data < iterPageEnd)
          {
                if (*((int*)data) == 0)
             {
               //not used, so skip it
               data = data + allocSize_;
               nodeOffset_++;
             }
              else
             {
               return data +sizeof(int);
             }
          }
       }
      return NULL;

} //ChunkIterator::nextElement()

